import common from '../../utils/common.js'
import classes from '../../utils/class.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      address_name: null,
      county_id: null
    },
    array: classes.classes,
    multiArray: [classes.grade_1, classes.grade_2[1]],
    multiIndex: [1, 0],
    multiArrayArea: [],
    multiIndexArea: [29, 5, 0],
    $toast: {
      show: false,
      text: ''
    },
    provinces: [],
    province: "",
    citys: [],
    city: "",
    countys: [],
    county: '',
    value: [0, 0, 0],
    values: [0, 0, 0],
    condition: false,
    fromPage:''
  },
  editLogo() {
    let self = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log('成功获取头像', res)
        var tempFilePaths = res.tempFilePaths
        var tempFiles = res.tempFiles
        if (tempFiles[0].size > 1048576) {
          return common.showToast(self, '图片过大')
        }
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePaths[0], //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            let head_img = 'data:image/jpeg;base64,' + res.data
            self.setData({
              [`userInfo.head_img`]: head_img
            }, () => {
              app.getToken(token => {
                app.getApi.updateImg({
                  token: token,
                  head_img: head_img
                }).then(res => {
                  if (res.code != 3000) {
                    common.showToast(self, res.message)
                  } else {
                    common.showToast(self, '头像修改成功')
                  }
                })
              })
            })
          }
        })
      },
      fail(erro) {
        console.log('头像获取失败', erro)
      }
    })
  },
  changeRegin(e) {
    console.log(e)
    let type = e.currentTarget.dataset.type
    let value = e.detail.value
    if (type == 'class') {
      value = this.data.array[value]
    } else {
      value = String(e.detail.value).replace(/,/g, '')
    }
    this.setData({ [`userInfo.${type}`]: value });
  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let value = e.detail.value
    let multiArray = this.data.multiArray
    this.setData({
      [`userInfo.grade`]: multiArray[1][value[1]]
    })
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let self = this
    let data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = classes.grade_2[0];
            break;
          case 1:
            data.multiArray[1] = classes.grade_2[1];
            break;
          case 2:
            data.multiArray[1] = classes.grade_2[2];
            break;
          case 3:
            data.multiArray[1] = classes.grade_2[3];
            break;
        }
        data.multiIndex[1] = 0;
        break;
    }
    this.setData(data);
  },
  bindMultiPickerChangeArea(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let value = e.detail.value
    let multiArrayArea = this.data.multiArrayArea
    let province = multiArrayArea[0] ? multiArrayArea[0][value[0]].city_name : ''
    let city = multiArrayArea[1] ? multiArrayArea[1][value[1]].city_name : ''
    let county = multiArrayArea[2] ? multiArrayArea[2][value[2]].city_name : ''
    this.setData({
      [`userInfo.address_name`]: province + city + county,
      [`userInfo.county_id`]: multiArrayArea[2][value[2]].id,
      [`userInfo.school_name`]: '',
      [`userInfo.grade`]: '',
      [`userInfo.class`]:''
    })
  },
  bindMultiPickerColumnChangeArea(e) {
    console.log('地址修改的列为', e.detail.column, '，值为', e.detail.value);
    let self = this
    let data = {
      multiArrayArea: this.data.multiArrayArea,
      multiIndexArea: this.data.multiIndexArea
    };
    let column = e.detail.column
    let value = e.detail.value
    switch (e.detail.column) {
      case 0:
        data.multiArrayArea[1] = []
        data.multiArrayArea[2] = []
        data.multiIndexArea = [value, 0, 0]
        self.setData(data, () => {
          self.findaddress(data.multiArrayArea[0][value][`id`])
        })
        break;
      case 1:
        data.multiArrayArea[2] = []
        data.multiIndexArea[1] = value
        data.multiIndexArea[2] = 0
        self.setData(data, () => {
          self.findaddress(data.multiArrayArea[0][data.multiIndexArea[0]][`id`], data.multiArrayArea[1][value][`id`])
        })
        break;
      case 2:
        data.multiIndexArea[2] = value
        self.setData(data);
        break;
    }
  },
  findaddress(province_id = '', city_id = '') {
    let self = this
    let multiArrayArea = this.data.multiArrayArea
    let multiIndexArea = this.data.multiIndexArea
    app.getApi.findaddress({ province_id: province_id, city_id: city_id }).then(res => {
      if (res.code == 3000) {
        if (province_id == '' && city_id == '') { //首次加载
          multiArrayArea.push(res.data.province_list)
          multiArrayArea.push(res.data.city_list)
          multiArrayArea.push(res.data.county_list)
        }
        if (province_id != '' && city_id == '') { //省份选择
          multiArrayArea[1] = res.data.city_list
          self.findaddress(multiArrayArea[0][multiIndexArea[0]][`id`], res.data.city_list[0].id)
        }
        if (province_id != '' && city_id != '') { //县级选择
          multiArrayArea[2] = res.data.county_list
        }
        console.log("multiArrayArea====>", multiArrayArea)
        self.setData({
          multiArrayArea: multiArrayArea
        })
      }
    })
  },
  editRouter(e) {
    let url = e.currentTarget.dataset.url
    let name = this.data.userInfo.school_name || ''
    let county_id = this.data.userInfo.county_id
    if (!county_id) {
      return common.showToast(self, '未获取到county_id,请选择地址')
    }
    wx.navigateTo({
      url: `${url}?name=${name}&county_id=${county_id}`
    })
  },
  onInput(e) {
    this.setData({
      [`userInfo.user_name`]: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    self.findaddress()
    if (options.fromPage){
      self.setData({
        fromPage: options.fromPage
      })
    }
    app.getToken(token => {
      app.getApi.getUserInfo({ token: token }).then(res => {
        if (res.code == 3000) {
          self.setData({
            userInfo: res.data
          })
        } else {
          common.showToast(self, res.message)
        }
      })
    })
  },
  saveUserInfo() {
    let self = this
    let u = this.data.userInfo
    if (!u) {
      return common.showToast(self, '请填写完整用户信息')
    }
    if (!u.user_name) {
      return common.showToast(self, '请输入姓名')
    }
    if (!u.address_name) {
      return common.showToast(self, '请选择学校地址')
    }
    if (!u.school_name) {
      return common.showToast(self, '请输入学校')
    }
    if (!u.grade) {
      return common.showToast(self, '请选择年级')
    }
    if (!u.class) {
      return common.showToast(self, '请选择班级')
    }
    app.getToken(token => {
      app.getApi.saveUserInfo({
        token: token,
        school_address: u.address_name,
        school_name: u.school_name,
        grade_name: u.grade,
        class_name: u.class,
        user_name: u.user_name,
        county_id: u.county_id
      }).then(res => {
        if (res.code != 3000) {
          common.showToast(self, res.message)
        } else {
          common.showToast(self, '修改成功')
          setTimeout(()=>{
            if (self.data.fromPage == 'index'){ //首页刷新
              wx.switchTab({
                url:'../index/index'
              })
            }else{
              wx.navigateBack({
                delta: -1
              })
            }
          },1000)
        }
      })
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '天天享读，让图书传递爱',
      imageUrl: '../../assets/images/index_s.png',
      path: '/pages/index/index'
    }
  }
})